// pages/profile/profile.ts
Page({
  data: {
    user: {
      name: '',
      gender: '',
      hobby: '',
      undergraduate: '',
      target: ''
    },
    genderList: ['男', '女'],
    genderIndex: 0
  },

  onLoad() {
    const userId = wx.getStorageSync('userId')
    // if (!userId) {
    //   wx.navigateTo({
    //     url: '/pages/login/login'
    //   })
    //   return
    // }

    wx.request({
      url: `http://localhost:8080/user/profile/${userId}`,
      method: 'GET',
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult) => {
        const response = res.data as { code: number; data: any; message: string }
        if (response.code === 200) {
          const genderIndex = this.data.genderList.indexOf(response.data.gender)
          this.setData({
            user: response.data,
            genderIndex: genderIndex !== -1 ? genderIndex : 0
          })
        } else {
          wx.showToast({
            title: response.message,
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  onNameInput(e: WechatMiniprogram.Input) {
    this.setData({
      'user.name': e.detail.value
    })
  },

  onGenderChange(e: WechatMiniprogram.PickerChange) {
    const index = Number(e.detail.value)
    this.setData({
      genderIndex: index,
      'user.gender': this.data.genderList[index]
    })
  },

  onHobbyInput(e: WechatMiniprogram.Input) {
    this.setData({
      'user.hobby': e.detail.value
    })
  },

  onUndergraduateInput(e: WechatMiniprogram.Input) {
    this.setData({
      'user.undergraduate': e.detail.value
    })
  },

  onTargetInput(e: WechatMiniprogram.Input) {
    this.setData({
      'user.target': e.detail.value
    })
  },

  updateProfile() {
    const userId = wx.getStorageSync('userId')
    if (!this.data.user.name || !this.data.user.hobby || 
        !this.data.user.undergraduate || !this.data.user.target) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    wx.request({
      url: `http://localhost:8080/user/profile/${userId}`,
      method: 'PUT',
      data: this.data.user,
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult) => {
        const response = res.data as { code: number; message: string }
        if (response.code === 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: response.message,
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  logout() {
    wx.removeStorageSync('userId')
    wx.showToast({
      title: '已退出登录',
      icon: 'success'
    })
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
})